<template>
	<view class="profile-container">
		<!-- 顶部背景 -->
		<view class="profile-header">
			<!-- 返回按钮 -->
			<u-icon name="arrow-left" size="28" color="#fff" class="back-icon" @click="handleBack" />
			<view class="user-info">
				<!-- 用户头像（可点击上传） -->
				<u-image
					:src="userInfo.avatar"
					class="user-avatar"
					:width="80"
					:height="80"
					:mode="aspectFill"
					shape="circle"
					@click="clickHandler"
				></u-image>
				<view class="user-details">
					<text class="user-name">{{ userInfo.nickname }}</text>
					<text class="user-bio">{{ userInfo.email }}</text>
				</view>
			</view>
			<!-- 配置图标 -->
			<u-icon name="setting" size="28" color="#fff" class="setting-icon" @click="showActionSheet" />
		</view>

		<!-- 操作菜单 -->
		<u-action-sheet :show="showActions" :actions="actions" @select="handleActionSelect" @close="showActions = false" />

		<!-- 中间显示用户信息 -->
		<view class="info-container">
			<view class="info-title">用户信息</view>
			<view class="info-content">
				<!-- 加载状态 -->
				<u-loading-icon v-if="loading" mode="circle" size="40" color="#6a11cb"></u-loading-icon>
				<!-- 错误提示 -->
				<view v-else-if="error" class="error-tip">
					<text>加载失败，请重试</text>
					<u-button type="primary" size="mini" @click="refetchUserProfile">重试</u-button>
				</view>
				<!-- 用户信息 -->
				<u-cell-group v-else>
					<u-cell title="用户名" :value="userData.username" />
					<u-cell title="昵称" :value="userData.nickname" />
					<u-cell title="邮箱" :value="userData.email" />
					<u-cell title="手机号" :value="userData.mobile" />
					<u-cell title="性别" :value="userData.sex === 1 ? '男' : '女'" />
				</u-cell-group>
			</view>
		</view>

		<!-- 底部导航栏 -->
		<!-- <btools></btools> -->
	</view>
</template>

<script setup>
import { ref, onMounted, onActivated } from 'vue';
import httpUrl from '@/config';
import btools from '@/components/btools.vue';

// 用户信息
const userInfo = ref({
	avatar: 'https://via.placeholder.com/150', // 默认头像
	nickname: '', // 用户昵称
	email: '', // 用户邮箱
	mobile: ',',
	sex: 1,
});

// 用户数据
const userData = ref({
	username: '',
	nickname: '',
	email: '',
	mobile: '',
	sex: 2, // 1: 女, 2: 男
});

// 操作菜单状态
const showActions = ref(false);

// 操作菜单选项
const actions = ref([
	{ name: '修改资料', icon: 'edit-pen' },
	{ name: '修改密码', icon: 'lock' },
	{ name: '退出登录', icon: 'close', color: 'red' }, // 退出登录选项
]);

// 当前选中的底部导航栏项
const currentTab = ref(1);

// 加载状态
const loading = ref(true);

// 错误状态
const error = ref(false);

// 返回上一页
const handleBack = () => {
	uni.switchTab({
		url: '/pages/index/index',
	});
};

// 显示操作菜单
const showActionSheet = () => {
	showActions.value = true;
};

// 处理操作菜单选择
const handleActionSelect = (action) => {
	showActions.value = false;
	switch (action.name) {
		case '修改资料':
			handleEditProfile();
			break;
		case '修改密码':
			handleChangePassword();
			break;
		case '退出登录':
			handleLogout();
			break;
	}
};

// 修改资料
const handleEditProfile = () => {
	// uni.showToast({
	// 	title: '跳转到修改资料页面',
	// 	icon: 'none',
	// });
	// 实际开发中可以跳转到修改资料页面
	uni.navigateTo({
		url: '/pages/profile/edit',
	});
};

// 修改密码
const handleChangePassword = () => {
	uni.showToast({
		title: '跳转到修改密码页面',
		icon: 'none',
	});
	uni.navigateTo({
		url: '/pages/profile/change-password',
	});
	// 实际开发中可以跳转到修改密码页面
};

// 上传头像/system/user/profile/update-avatar
const clickHandler = () => {
	uni.chooseFile({
		success: async (res) => {
			const tempFilePath = res.tempFilePaths[0];
			userInfo.value.avatar = tempFilePath;
			await uploadFile(tempFilePath);
		},
	});
};
const uploadFile = (fielpath) => {
	const tenantId = uni.getStorageSync('tenantId');
	const accessToken = uni.getStorageSync('accessToken');
	uni.uploadFile({
		header: {
			Accept: '*/*',
			'Tenant-Id': tenantId,
			Authorization: `Bearer ${accessToken}`,
		},

		url: httpUrl.baseUrl + '/system/user/profile/update-avatar', // 服务器上传地址
		filePath: fielpath, // 本地文件路径
		name: 'avatarFile',
		success: (res) => {
			uni.showToast({
				title: '头像上传成功',
				icon: 'success',
			});
		},
		fail: (err) => {
			console.log('上传失败:', err);
		},
		complete: () => {
			console.log('上传完成');
		},
	});
};
// 退出登录
const handleLogout = () => {
	uni.showModal({
		title: '提示',
		content: '确定要退出登录吗？',
		success: (res) => {
			if (res.confirm) {
				// 清除用户登录状态
				uni.removeStorageSync('userId');
				uni.removeStorageSync('accessToken');
				uni.removeStorageSync('refreshToken');
				uni.removeStorageSync('expiresTime');
				uni.removeStorageSync('tenantId');
				uni.removeStorageSync('userProfile');
				uni.showToast({
					title: '退出成功',
					icon: 'success',
				});
				// 跳转到登录页面
				uni.navigateTo({
					url: '/pages/login/login',
				});
			}
		},
	});
};
let fetchUserProfile;
let refetchUserProfile;
// 获取用户信息
refetchUserProfile = () => {
	let token = uni.getStorageSync('refreshToken');
	fetchUserProfile(token);
};
fetchUserProfile = (token) => {
	console.log('=================111=========');
	loading.value = true;
	error.value = false;

	const tenantId = uni.getStorageSync('tenantId');
	const accessToken = uni.getStorageSync('refreshToken');

	uni.request({
		url: httpUrl.baseUrl + '/system/user/profile/get',
		method: 'GET',
		header: {
			'Tenant-Id': tenantId,
			Authorization: `Bearer ${accessToken}`,
		},
		success: (res) => {
			if (res.data.code === 0) {
				const profile = res.data.data;
				userData.value = {
					username: profile.username,
					nickname: profile.nickname,
					email: profile.email,
					mobile: profile.mobile,
					sex: profile.sex,
				};
				userInfo.value = {
					avatar: profile.avatar || 'https://via.placeholder.com/150',
					nickname: profile.nickname,
					email: profile.email,
				};
				// 缓存用户信息
				uni.setStorageSync('userProfile', profile);
			} else {
				error.value = true;
				uni.showToast({
					title: '获取用户信息失败',
					icon: 'none',
				});
			}
		},
		fail: (err) => {
			console.error('请求失败:', err);
			error.value = true;
			uni.showToast({
				title: '网络请求失败',
				icon: 'none',
			});
		},
		complete: () => {
			loading.value = false;
		},
	});
};
// 使用 onActivated 钩子监听页面每次显示时的行为
onActivated(() => {
	uni.$on('refreshUserData', () => {
		// 刷新数据逻辑
		fetchUserProfile();
	});
});
// 页面加载时获取用户信息
onMounted(() => {
	const cachedProfile = uni.getStorageSync('userProfile');
	let token = uni.getStorageSync('accessToken');
	if (cachedProfile) {
		userData.value = {
			username: cachedProfile.username,
			nickname: cachedProfile.nickname,
			email: cachedProfile.email,
			mobile: cachedProfile.mobile,
			sex: cachedProfile.sex,
		};
		userInfo.value = {
			avatar: cachedProfile.avatar || 'https://via.placeholder.com/150',
			nickname: cachedProfile.nickname,
			email: cachedProfile.email,
		};
	}
	fetchUserProfile(token);
});

// 处理底部导航栏切换
const handleTabChange = (index) => {
	currentTab.value = index;
	if (index === 0) {
		uni.redirectTo({
			url: '/pages/index/index',
		});
	} else if (index === 1) {
		uni.redirectTo({
			url: '/pages/my/my',
		});
	}
};
</script>

<style scoped>
/* 页面容器 */
.profile-container {
	display: flex;
	flex-direction: column;
	height: 100vh;
	background-color: #f5f5f5;
}

/* 顶部背景 */
.profile-header {
	position: relative;
	height: 200px;
	background: linear-gradient(135deg, #6a11cb, #2575fc);
	padding: 20px;
	display: flex;
	align-items: center;
	justify-content: space-between;
}

/* 返回按钮 */
.back-icon {
	position: absolute;
	left: 20px;
	top: 20px;
	cursor: pointer;
}

/* 用户信息 */
.user-info {
	display: flex;
	align-items: center;
	margin-left: 50px; /* 为返回按钮留出空间 */
}
.user-avatar {
	margin-right: 15px;
	cursor: pointer;
}
.user-details {
	display: flex;
	flex-direction: column;
}
.user-name {
	font-size: 20px;
	font-weight: bold;
	color: #fff;
}
.user-bio {
	font-size: 14px;
	color: rgba(255, 255, 255, 0.8);
	margin-top: 5px;
}

/* 配置图标 */
.setting-icon {
	cursor: pointer;
}

/* 用户信息容器 */
.info-container {
	margin: 20px;
	padding: 20px;
	background-color: #fff;
	border-radius: 10px;
	box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
}

/* 用户信息标题 */
.info-title {
	font-size: 18px;
	font-weight: bold;
	color: #333;
	margin-bottom: 15px;
}

/* 用户信息内容 */
.info-content {
	font-size: 14px;
	color: #666;
}

/* 错误提示 */
.error-tip {
	display: flex;
	flex-direction: column;
	align-items: center;
	gap: 10px;
}
</style>
